#!/bin/bash -e

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
    echo "Illegal number of parameters"
    exit 1
fi

TAG=$1
DRY_RUN=""
[ "$#" -eq 2 ] && DRY_RUN=$2

echo "---- Build Discuz Q Docker Image -----------------------------"

[ "$DRY_RUN" = "-n" ] && echo "Dry run, no changes will be pushed to remote"

# docker 镜像远端仓库
DOCKER_REPO="discuz/dzq"
# docker 无数据库镜像远端仓库
DOCKER_NO_DB_REPO="discuz/dzq-no-db"

BASE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd $BASE

function check_discuz {
    cd $BASE
    if [ -d dzfull_temp ]; then
        echo "---- dzfull_temp exists"
    else
        ./build_vendor $TAG -n
    fi
}

function move_dz_into_docker {
    rm -rf $BASE/dzq-docker/root/var/www/discuz/*
    rm -rf $BASE/dzq-docker-no-db/root/var/www/discuz/*
    rm -f $BASE/dzfull_temp/*.zip
    mkdir -p $BASE/dzq-docker/root/var/www/discuz/
    cp -r $BASE/dzfull_temp/* $BASE/dzq-docker/root/var/www/discuz/
    mkdir -p $BASE/dzq-docker-no-db/root/var/www/discuz/
    mv $BASE/dzfull_temp/* $BASE/dzq-docker-no-db/root/var/www/discuz/
    rm -rf $BASE/dzfull_temp
}

function build_docker {
    cd $BASE/dzq-docker
    docker build -t tencent/dzq:$TAG .
    cd $BASE/dzq-docker-no-db
    curl https://discuzq-docs-1258344699.cos.ap-guangzhou.myqcloud.com/setup.php -o root/usr/sbin/setup.php

    rm -f root/usr/sbin/linux_stargate_installer
    rm -f root/usr/sbin/cfs_barad_plugin_installer_release_v11

    docker build -t tencent/dzq-no-db:$TAG .
}

function push_docker {
    if [ "$DRY_RUN" = "-n" ]; then
        echo "---- Dry run, won't upload to ccr"
    elif [ "$DRY_RUN" = "-p" ]; then
        echo "---- uploading without latest tag"
        # 登录社区共有镜像仓库
        docker tag tencent/dzq:$TAG $DOCKER_REPO:$TAG
        docker push $DOCKER_REPO:$TAG
        docker tag tencent/dzq-no-db:$TAG $DOCKER_NO_DB_REPO:$TAG
        docker push $DOCKER_NO_DB_REPO:$TAG
    else 
        echo "---- uploading to registry.discuz.chat"
        docker tag tencent/dzq:$TAG $DOCKER_REPO:$TAG
        docker push $DOCKER_REPO:$TAG
        docker tag tencent/dzq-no-db:$TAG $DOCKER_NO_DB_REPO:latest
        docker push $DOCKER_NO_DB_REPO:latest
    fi    
}

if [ "$DRY_RUN" = "-r" ]; then
    echo "---- rebuilding docker image only"
    build_docker
    push_docker
else
    check_discuz
    move_dz_into_docker
    build_docker
    push_docker
fi